package com.hz.tgb.api.invoice.pdf.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @author hezhao on 2018/9/18 16:16
 */
public class PDFStringUtil {
    private static final Logger logger = LoggerFactory.getLogger(PDFStringUtil.class);

    public PDFStringUtil() {
    }

    public static int parseInt(String numeric) {
        if (isNumeric(numeric)) {
            return StringUtils.isBlank(numeric) ? 0 : Integer.parseInt(numeric.trim());
        }

        return 0;
    }

    public static long parseLong(String numeric) {
        return StringUtils.isBlank(numeric) ? 0L : Long.parseLong(numeric.trim());
    }

    public static float parseFloat(String numeric) {
        return StringUtils.isBlank(numeric) ? 0.0F : Float.parseFloat(numeric.trim());
    }

    public static double parseDouble(String numeric) {
        return StringUtils.isBlank(numeric) ? 0.0D : Double.parseDouble(numeric.trim());
    }

    public static BigDecimal parseDecimal(String numeric) {
        if (StringUtils.isBlank(numeric)) {
            return BigDecimal.ZERO;
        } else {
            numeric = numeric.replaceAll(",", "");
            return (new BigDecimal(numeric.trim())).setScale(2, 4);
        }
    }

    public static <T> String getString(T value) {
        return value == null ? "" : value.toString();
    }

    public static String getChinese(int number) {
        return null;
    }

    public static <T> String join(String split, T... array) {
        if (array != null && array.length != 0) {
            if (split == null) {
                split = "";
            }

            StringBuilder result = new StringBuilder(getString(array[0]));

            for(int i = 1; i < array.length; ++i) {
                result.append(split).append(array[i]);
            }

            return result.toString();
        } else {
            return "";
        }
    }

    public static Map<String, String> convertMap(Map<String, Object> param) {
        HashMap map = new HashMap();
        if (MapUtils.isNotEmpty(param)) {
            Iterator<Map.Entry<String, Object>> iterator = param.entrySet().iterator();
            while(iterator.hasNext()) {
                Map.Entry<String, Object> next = iterator.next();
                if (next.getValue() == null) {
                    map.put(next.getKey(), "");
                } else {
                    map.put(next.getKey(), String.valueOf(next.getValue()));
                }
            }
            return map;
        } else {
            return map;
        }
    }

    public static List<Map<String, String>> convertMap(List<Map<String, Object>> maps) {
        ArrayList tempList = new ArrayList();
        if (CollectionUtils.isNotEmpty(maps)) {
            Iterator<Map<String, Object>> mapsIterator = maps.iterator();
            while(mapsIterator.hasNext()) {
                Map<String, Object> param = mapsIterator.next();
                HashMap map = new HashMap(param.size());
                Iterator<Map.Entry<String, Object>> iterator = param.entrySet().iterator();
                while(iterator.hasNext()) {
                    Map.Entry<String, Object> next = iterator.next();
                    if (next.getValue() == null) {
                        map.put(next.getKey(), "");
                    } else {
                        map.put(next.getKey(), String.valueOf(next.getValue()));
                    }
                }

                tempList.add(map);
            }

            return tempList;
        } else {
            return tempList;
        }
    }

    public static List<Map<String, Object>> convertMap2(List<Map<String, Object>> maps) {
        ArrayList tempList = new ArrayList();
        if (maps != null && maps.size() != 0) {
            Iterator<Map<String, Object>> mapsIterator = maps.iterator();
            while(mapsIterator.hasNext()) {
                Map<String, Object> param = mapsIterator.next();
                HashMap map = new HashMap(param.size());
                Iterator<Map.Entry<String, Object>> iterator = param.entrySet().iterator();
                while(iterator.hasNext()) {
                    Map.Entry<String, Object> next = iterator.next();
                    if (next.getValue() == null) {
                        map.put(next.getKey(), "");
                    } else if (next.getValue() instanceof JSONArray) {
                        map.put(next.getKey(), next.getValue());
                    } else {
                        map.put(next.getKey(), String.valueOf(next.getValue()));
                    }
                }
                tempList.add(map);
            }
            return tempList;
        } else {
            return tempList;
        }
    }

    public static String replaceSubString(String source, int start, int end) {
        if (StringUtils.isBlank(source)) {
            return "";
        } else {
            String sub = "";
            String startSub;
            String endSub;

            try {
                startSub = source.substring(0, start);
                endSub = source.substring(end, source.length());
                // source.substring(start, end);
                StringBuilder sb = new StringBuilder();
                for(int i = 0; i < end - start; ++i) {
                    sb = sb.append("*");
                }
                sub = startSub + sb.toString() + endSub;
            } catch (Exception var8) {
                logger.error("出现异常", var8);
            }

            return sub;
        }
    }

    public static String replaceSubString(String str, int begin) {
        String sub = "";

        try {
            sub = str.substring(0, begin);
            StringBuilder sb = new StringBuilder();

            for(int i = 0; i < str.length() - begin; ++i) {
                sb = sb.append("*");
            }

            sub = sub + sb.toString();
        } catch (Exception var5) {
            logger.error("出现异常", var5);
        }

        return sub;
    }

    public static String replaceIdNumber(String source) {
        if (StringUtils.isBlank(source)) {
            return "";
        } else {
            int len = source.length();
            StringBuilder sb = new StringBuilder();

            try {
                if (len == 15) {
                    sb.append(source, 0, 8);
                    sb.append("***");
                    sb.append(source, 12, 15);
                } else if (len == 18) {
                    sb.append(source, 0, 10);
                    sb.append("***");
                    sb.append(source, 14, 18);
                } else {
                    sb.append(source, 0, len > 8 ? len - 8 : 1);
                    sb.append("***");
                    sb.append(source, len > 4 ? len - 4 : 0, len);
                }
            } catch (Exception var4) {
                logger.error("出现异常", var4);
            }

            return sb.toString();
        }
    }

    public static String getLastestStr(String source, int count) {
        if (StringUtils.isBlank(source)) {
            return "";
        } else {
            return source.length() <= count ? source : source.substring(source.length() - count);
        }
    }

    public static String replacePhone(String source) {
        if (StringUtils.isBlank(source)) {
            return "";
        } else {
            StringBuilder sb = new StringBuilder();

            try {
                String subTemp = source.substring(0, 4);
                sb.append(subTemp);
                sb.append("****");
                if (source.length() >= 11) {
                    subTemp = source.substring(8, 11);
                    sb.append(subTemp);
                }
            } catch (Exception var3) {
                logger.error("出现异常", var3);
            }

            return sb.toString();
        }
    }

    public static String getPrice(String priceStr) {
        if (priceStr != null && !"0".equals(priceStr)) {
            priceStr = priceStr.trim();
            if (priceStr.contains(".")) {
                if (priceStr.length() < 7) {
                    return priceStr + "元";
                }

                priceStr = priceStr.substring(0, priceStr.indexOf("."));
            }

            int len = priceStr.length();
            StringBuilder priceBuffer = new StringBuilder();
            if (len > 8) {
                priceBuffer.append(priceStr, 0, len - 8);
                if (len % 4 > 0) {
                    priceBuffer.append(".");
                    priceBuffer.append(priceStr, 0, len % 4);
                }

                priceBuffer.append("亿");
            } else if (len > 4) {
                priceBuffer.append(priceStr, 0, len - 4);
                if (len % 4 > 0) {
                    priceBuffer.append(".");
                    priceBuffer.append(priceStr, len - 4, 4);
                }

                priceBuffer.append("万");
            } else {
                priceBuffer.append(priceStr);
                priceBuffer.append("元");
            }

            return priceBuffer.toString();
        } else {
            return null;
        }
    }

    public static String getNickFromPhone(String phone) {
        if (StringUtils.isBlank(phone)) {
            return "未知名称";
        } else {
            StringBuilder nickBuffer = new StringBuilder();
            if (phone.length() >= 3) {
                nickBuffer.append(phone, 0, 3);
            }

            if (phone.length() >= 7) {
                nickBuffer.append("***");
            }

            if (phone.length() >= 11) {
                nickBuffer.append(phone, 7, 11);
            }

            return nickBuffer.toString();
        }
    }

    public static boolean isMobile(String userAgent, String type) {
        boolean flag = false;
        if (userAgent != null && type != null) {
            if ("mobile".equals(type.toLowerCase())) {
                flag = userAgent.toLowerCase().matches("/applewebkit.*mobile.*/");
            } else if ("android".equals(type.toLowerCase())) {
                flag = userAgent.toLowerCase().contains("android");
            } else if ("iphone".equals(type.toLowerCase())) {
                flag = userAgent.toLowerCase().contains("iphone");
            } else if ("ipad".equals(type.toLowerCase())) {
                flag = userAgent.toLowerCase().contains("ipad");
            }
            return flag;
        } else {
            return false;
        }
    }

    public static String removeComma(String str) {
        return str == null ? null : str.trim().replaceAll(",", "");
    }

    public static long getLongValueFromJson(JSONObject jsonObject, String key) {
        try {
            return jsonObject.getLong(key);
        } catch (Exception var3) {
            return 0L;
        }
    }

    public static int getIntValueFromJson(JSONObject jsonObject, String key) {
        try {
            return jsonObject.getInteger(key);
        } catch (Exception var3) {
            return 0;
        }
    }

    public static BigDecimal getBigDecimalFromJson(JSONObject jsonObject, String key) {
        try {
            return jsonObject.getBigDecimal(key);
        } catch (Exception var3) {
            return BigDecimal.ZERO;
        }
    }

    public static final boolean isNumeric(String s) {
        return (s != null && !"".equals(s.trim())) && s.matches("^[0-9]*$");
    }

    private static final Pattern PATTERN_FILTRATION = Pattern.compile("[`~!@#$%^&*()+=|{}:;\\\\[\\\\]<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]");
    public static String filtration(String str) {
        String result = str;
        try {
            result = PATTERN_FILTRATION.matcher(str).replaceAll("").trim();
        } catch (Exception var4) {
            logger.error("出现异常", var4);
        }
        return result;
    }

    private static final Pattern PATTERN_REMOVE_SPACE = Pattern.compile("[ 　]");
    public static String removeSpace(String str) {
        String result = str;
        try {
            result = PATTERN_REMOVE_SPACE.matcher(str).replaceAll("").trim();
        } catch (Exception var4) {
            logger.error("出现异常", var4);
        }
        return result;
    }

//    public static void main(String[] args) {
//        System.out.println(removeSpace("校 验 码:"));
//        System.out.println(getLastestStr("123fee23423", 4));
//        System.out.println(getLastestStr((String)null, 4));
//        System.out.println(getLastestStr("123", 4));
//        System.out.println(getLastestStr("1234", 4));
//        System.out.println(getLastestStr("12345", 4));
//    }

}
